//
//  SchoolWebViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/24.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import WebKit

class SchoolWebViewController: KMViewController {

    ///webview
    fileprivate var webView : WKWebView!
    
    ///链接
    fileprivate var urlStr  = ""
    
    ///进度条
    fileprivate let progressView = UIProgressView()
    
    //移除html标签
    var removeElements = ["shead header","app-download"]
    
    
    init(urlString:String?,title:String? = "") {
        super.init(nibName: nil, bundle: nil)
        
        self.urlStr = urlString ?? ""
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        progressView.trackTintColor = UIColor.clear
        progressView.progressTintColor = UIColor.moveColor()
        self.view.addSubview(progressView)
        
        progressView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 5))
        }
        
        createWebView()
        
        self.view.bringSubview(toFront: progressView)
        
    }
    
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    fileprivate func createWebView() {
        
        self.webView = WKWebView.init(frame: .zero)
        
        let string = self.urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let url = URL.init(string: string ?? "") {
            let request = URLRequest.init(url: url)
            webView.load(request)
        }
        webView.navigationDelegate = self
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if "estimatedProgress" == keyPath {
            self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.progressView.progress == 0 {
                self.progressView.isHidden = false
            }else if self.progressView.progress == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    if self.progressView.progress == 1 {
                        self.progressView.progress = 0
                        self.progressView.isHidden = true
                    }
                }
            }
        }
        
        let removeElement = KMTool.removeHtmlElement(classNames: removeElements)
        self.webView.evaluateJavaScript(removeElement, completionHandler: nil)
        
        let removeFooter = "document.getElementsByTagName('ul')[1].remove();"
        self.webView.evaluateJavaScript(removeFooter, completionHandler: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension SchoolWebViewController : WKNavigationDelegate,WKUIDelegate {
    
    //MARK: 页面加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        MyLog(global_requestFailed)
    }
    
    
    
    //MARK: 页面加载成功
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        MyLog(global_loadSuccess)
    }
}
